<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="nav">
        <a href="#/page1" class="page">page1</a>
        <a href="#/page2" class="page">page2</a>
        <a href="#/page3" class="page">page3</a>
    </div>
    <div id="container"></div>
    <script>
        // window.addEventListener('hashchange',function(event){
        //     let newURL = event.newURL;
        //     let oldURL = event.oldURL;
        //     // console.log(newURL,oldURL,'---');
        //     let router=newURL.split('#/')[1];
        //     // console.log(router);
        // })
        class HashRouter{
            // 事件监听
            // 配置 {}
            // key -> val
            constructor(){
                this.hashURLobj={};
                window.addEventListener('hashchange',(event)=>{
                    let newURL = event.newURL;
                    // console.log(newURL,oldURL,'---');
                    if(newURL.indexOf('#')==-1)return ;
                    let router=newURL.split('#')[1];
                    console.log(router,this.hashURLobj);
                    const callback=this.hashURLobj[router];
                    if(newURL && typeof callback=='function'){
                        callback();
                    }
                    })
            }
            register(key,fun){
                this.hashURLobj[key]=fun.bind(this);
            }
        }
        let router=new HashRouter();        // 路由实例
        let container=document.getElementById('container'); // 挂载点
        router.register('/page1',()=>{
            console.log('1')
            container.innerHTML='我是page1';
        })
        router.register('/page2',()=>{
            console.log('2')
            container.innerHTML='我是page2';
        })
        router.register('/page3',()=>{
            console.log('3')
            container.innerHTML='我是page3';
        })
    </script>
</body>
</html>